<template>
  <!-- 主变负载点击负载率跳转的二级页面 -->
  <div class="container">
    <div class="container-top">
      <div class="back" @click="goBack"></div>
    </div>
    <div class="head borderStyle centerbox relative">
      <div class="title centertitleStyle centerbox title-relative">主变负载</div>
      <!-- 主变负载详情页中部 -->
      <div
        class="echa"
        v-loading="fzlLoading"
        element-loading-text="数据加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <v-chart :auto-resize="true" :options="newOption" @click="clickEvent" />
      </div>
    </div>
    <div class="center">
      <div class="inspection-report-h bigTableStyle">
        <div class="inspection-report-index">
          <div class="fromed">
            <el-form ref="elForm" :model="formData" :rules="rules" label-width="1.4rem">
              <el-row :gutter="15">
                <el-col :span="4">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-form-item label="所属单位:" prop="time">
                        <el-select
                          v-model="formData.company"
                          placeholder="请选择"
                          :style="{width: '100%'}"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="(item, index) in CompanyList"
                            :key="index"
                            :label="item.name"
                            :value="item.code"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="4">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-form-item label="维护班组:" prop>
                        <el-select
                          v-model="formData.team"
                          placeholder="请选择"
                          :style="{width: '100%'}"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="(item, index) in TeamList"
                            :key="index"
                            :label="item.name"
                            :value="item.code"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="4">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-form-item label="变电站:" prop="source">
                        <el-select
                          v-model="formData.substation"
                          filterable
                          placeholder="请选择"
                          :style="{width: '100%'}"
                          clearable
                        >
                          <el-option
                            v-for="(item, index) in SubstationList"
                            :key="index"
                            :label="item.name"
                            :value="item.code"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="4">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-form-item label="电压等级:" prop="source">
                        <el-select
                          v-model="formData.Voltage"
                          placeholder="请选择"
                          :style="{width: '100%'}"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="(item, index) in VoltageList"
                            :key="index"
                            :label="item.name"
                            :value="item.code"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="4">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-form-item label="负载率(%):" prop="fzlStart">
                        <el-input
                          v-model="formData.fzlStart"
                          placeholder="请输入"
                          :style="{width: '100%'}"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="4">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-form-item label="至:" prop="fzlEnd">
                        <el-input
                          v-model="formData.fzlEnd"
                          placeholder="请输入"
                          :style="{width: '100%'}"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <el-row :gutter="15">
                <el-col :span="4">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-form-item label="油温(°C):" prop="ywStart">
                        <el-input
                          v-model="formData.ywStart"
                          placeholder="请输入"
                          :style="{width: '100%'}"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="4">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-form-item label="至:" prop="ywEnd">
                        <el-input
                          v-model="formData.ywEnd"
                          placeholder="请输入"
                          :style="{width: '100%'}"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="8">
                  <el-row :gutter="15">
                    <el-col :span="24">
                      <el-form-item label="监测时间:" prop="source">
                        <el-date-picker
                          :style="{width: '100%'}"
                          v-model="formData.jctime"
                          value-format="yyyy-MM-dd"
                          type="daterange"
                          align="right"
                          unlink-panels
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          :picker-options="pickerOptions"
                        ></el-date-picker>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-col>
                <el-col :span="4">
                  <div class="inspection-report-index-btn">
                    <el-button
                      class="table-query"
                      type="primary"
                      @click="submitForm"
                      icon="el-icon-search"
                    >查询</el-button>
                    <el-button class="table-query" type="primary" @click="resForm">重置</el-button>
                  </div>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="tableed">
            <el-table
            border
              :data="tableData"
              height="100%"
              :row-class-name="tableRowClassName"
              style="width: 100%;height:100%;"
            >
              <el-table-column prop="myIndex" width="70" label="序号" show-overflow-tooltip></el-table-column>
              <el-table-column prop="ssdsmc" label="所属单位" show-overflow-tooltip></el-table-column>
              <el-table-column prop="whbzmc" label="维护班组" show-overflow-tooltip></el-table-column>
              <el-table-column prop="pmsbdz" label="变电站" show-overflow-tooltip></el-table-column>
              <el-table-column prop="pmsdydjmc" label="电压等级(kV)" show-overflow-tooltip></el-table-column>
              <el-table-column prop="sbmc" label="主变名称" show-overflow-tooltip></el-table-column>
              <el-table-column prop="pvalue" label="无功功率(MVar)" show-overflow-tooltip></el-table-column>
              <el-table-column prop="qvalue" label="有功功率(MW)" show-overflow-tooltip></el-table-column>
              <el-table-column prop="edrl" label="额定容量(MVA)" show-overflow-tooltip></el-table-column>
              <el-table-column prop="fzl" label="负载率(%)" show-overflow-tooltip></el-table-column>
              <el-table-column prop="ywvalue" label="油温(°C)" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div>{{ scope.row.ywvalue==0?"-":scope.row.ywvalue }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="timer" label="监测时间" show-overflow-tooltip></el-table-column>
            </el-table>
          </div>
          <div class="paged elPaginationStyle">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pages.page"
              :page-sizes="[10, 20, 30]"
              :page-size="pages.pageSize"
              layout="total,prev, pager, next,sizes, jumper"
              :total="pages.totalSize"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import echarts from "echarts";
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import { EChartOption } from "echarts";
import { publicAPIModule } from "@/store/modules/public";
import { JointInspectionModule } from "@/store/modules/JointInspection";
//loadsh
import lodash from "lodash";
@Component({
  components: {
    // DefectsHead,
    // DefectsCenter,
    // DefectsBottom,
  },
})
export default class Defects extends Vue {
  // 所属地市
  // private localCity: string = "8a1ea5c64bdebad1014bdebc55c80162";
  // 所属地市
  get CompanyListlocalCity() {
    let CompanyList = JointInspectionModule.CompanyList || [];
    return CompanyList;
  }

  // 负载率柱状图数据
  private dutyBarData: any = {};
  //传图表得数据
  public xAxisData: any = ["人工发现", "自动巡检"];

  public option: Object = {
    tooltip: {
      trigger: "item",
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
      },
    },
    grid: {
      left: "2%",
      right: "4%",
      bottom: "14%",
      top: "16%",
      containLabel: true,
    },
    legend: {
      // left: 'center',
      right: "2%",
      top: "2%",
      textStyle: {
        color: "#fff",
      },
      itemWidth: 14,
      itemHeight: 12,
      // itemGap: 35
    },

    xAxis: {
      type: "category",
      data: [],
      axisLine: {
        lineStyle: {
          color: "rgba(115,129,167,0.8)",
        },
      },
      axisLabel: {
        interval: 0,
        // rotate: 40,
        color: "#fff",
        textStyle: {
          fontFamily: "Microsoft YaHei",
        },
      },
      axisTick: {
        show: false,
      },
    },

    yAxis: {
      type: "value",
      // name: "单位：个",
      axisLine: {
        show: false,
        lineStyle: {
          color: "white",
        },
      },
      splitLine: {
        show: true,
        lineStyle: {
          color: "rgba(255,255,255,0.1)",
        },
      },
      axisLabel: {},
      axisTick: {
        show: false,
      },
    },
    series: [
      {
        // name: (this as any).xAxisData[0],
        type: "bar",
        barWidth: "15%",
        barGap: 0, //柱间距离
        itemStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: "#38F7F2",
              },
              {
                offset: 1,
                color: "#264C9C",
              },
            ]),
            // barBorderRadius: 11,
          },
        },
        data: [],
      },
    ],
  };

  // 点击柱图切换表格数据
  private clickEvent(v: any) {
    // console.log("vvvvvvvvvv:", v);
    if (v.name === "80%以下") {
      this.formData.fzlStart = "0";
      this.formData.fzlEnd = "80";
      this.formData.fzlType = "80";
    } else if (v.name === "80%-100%") {
      this.formData.fzlStart = "80";
      this.formData.fzlEnd = "100";
      this.formData.fzlType = "100";
    } else if (v.name === "100%以上") {
      this.formData.fzlStart = "100";
      this.formData.fzlEnd = "";
      this.formData.fzlType = "100+";
    }
    this.queryAuxRealtimeList();
  }
  // 更新option
  get newOption() {
    // console.log("this.defectStatistics:", this.defectStatistics);
    let option = lodash.cloneDeep(this.option);
    let robotInspection = this.newMainLoadCount;
    let rgData = [
      robotInspection.typeOne,
      robotInspection.typeTwo,
      robotInspection.typeThree,
    ];
    let xData = ["80%以下", "80%-100%", "100%以上"];
    (option as any).series[0].data = rgData;
    (option as any).xAxis.data = xData;
    return option;
  }

  // 返回按钮
  private goBack(val: string) {
    window.history.back();
    // this.$router.push("index");
  }

  //搜索框from表单数据
  formData = {
    company: "", // 所属单位
    team: "", // 维护班组
    substation: "", // 变电站
    Voltage: "", // 电压等级
    jctime: [], // 监测时间
    fzlStart: "", // 开始负载率
    fzlEnd: "", // 结束负载率
    fzlType: "", // 负载率类型
    ywStart: "", // 开始油温
    ywEnd: "", // 结束油温
  };

  // 校验数字、正数、end大于start
  private validateNum(rule, value, callback) {
    // console.log("value:", /^\d*$/g.test(value));
    if (/^\d*$/g.test(value)) {
      callback();
    } else {
      callback(new Error("请输入数字"));
    }
  }

  // 前一个表单数据
  oldForm = {};
  jclxOptions: { [key: string]: any } = [];
  rules = {
    fzlStart: [
      {
        validator: this.validateNum,
        trigger: "change",
      },
    ],
    fzlEnd: [
      {
        validator: this.validateNum,
        trigger: "change",
      },
    ],
    ywStart: [
      {
        validator: this.validateNum,
        trigger: "change",
      },
    ],
    ywEnd: [
      {
        validator: this.validateNum,
        trigger: "change",
      },
    ],
  };
  pickerOptions = {
    shortcuts: [
      {
        text: "最近一周",
        onClick(picker: any) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit("pick", [start, end]);
        },
      },
      {
        text: "最近一个月",
        onClick(picker: any) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          picker.$emit("pick", [start, end]);
        },
      },
      {
        text: "最近三个月",
        onClick(picker: any) {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          picker.$emit("pick", [start, end]);
        },
      },
    ],
  };
  $refs!: {
    elForm: any;
  };

  // 下拉框单位名称
  get CompanyList() {
    let CompanyList = publicAPIModule.CompanyList || [];
    return CompanyList;
  }
  // 下拉框变电站
  get SubstationList() {
    let SubstationList = publicAPIModule.SubstationList || [];
    return SubstationList;
  }
  // 下拉框运维班组
  get TeamList() {
    let TeamList = publicAPIModule.TeamList || [];
    return TeamList;
  }
  // 下拉框变电站电压等级
  get VoltageList() {
    let VoltageList = publicAPIModule.VoltageList || [];
    return VoltageList;
  }
  searchValue = 0;
  // 查询
  submitForm() {
    // console.log("formdata:",this.formData)
    this.$refs.elForm.validate((valid: any) => {
      if (!valid) return;
      // TODO 提交表单
      // console.log(this.formData);
      this.pages.page = 1;
      this.searchValue = 1;
      this.queryAuxRealtimeList();
    });
  }
  // 刷新
  resForm() {
    this.pages.page = 1;
    this.formData = {
      company: "", // 所属单位
      team: "", // 维护班组
      substation: "", // 变电站
      Voltage: "", // 电压等级
      jctime: [], // 发现时间
      fzlStart: "", // 开始负载率
      fzlEnd: "", // 结束负载率
      fzlType: "", // 负载率类型
      ywStart: "", // 开始油温
      ywEnd: "", // 结束油温
    };
    this.queryAuxRealtimeList();
  }

  //table表格相关事件数据
  tableData = [
    // {
    //   dydj: "",
    //   edrl: 0,
    //   fzl: "",
    //   objId: "",
    //   pmsbdz: "",
    //   pmsdydj: "",
    //   pmsdydjmc: "",
    //   pmsid: "",
    //   ptimev: "",
    //   pvalue: 0,
    //   qvalue: 0,
    //   sbbm: "",
    //   sbmc: "",
    //   ssds: "",
    //   ssdsmc: "",
    //   timer: "",
    //   whbz: "",
    //   whbzmc: "",
    //   xh: "",
    //   ywvalue: 0,
    // },
  ];
  tableRowClassName({ row, rowIndex }: any): string {
    // console.log(row, rowIndex);
    if (rowIndex % 2 === 0) {
      return "row1";
    } else {
      return "row2";
    }
  }
  verify(scope: any) {
    // console.log(scope.row);
  }

  //分页数据事件相关
  pages: { pageSize: number; page: number; totalSize: number } = {
    pageSize: 20,
    page: 1,
    totalSize: 0,
  };
  //   分页
  handleSizeChange(val: any) {
    // console.log(`每页 ${val} 条`);
    this.pages.pageSize = val;
    this.pages.page = 1;
    this.queryAuxRealtimeList();
  }
  // 分页事件
  handleCurrentChange(val: any) {
    this.pages.page = val;
    this.queryAuxRealtimeList();
  }
  // 监听查询条件变化
  @Watch("formData", { immediate: true, deep: true })
  setCdType(newForm) {
    let oldForm: any = this.oldForm;
    // 如果变电站id变化
    if (newForm.station !== oldForm.station) {
      // this.formData.jclx = "";
      this.queryTypes();
    }
    this.oldForm = lodash.cloneDeep(newForm);
  }

  // 查询测点类型
  queryTypes() {
    let form = this.formData;
    let params = {
      // station: form.station,
      type: "fk",
    };
    (this as any).$services
      .queryTypes({ data: params })
      .then((result: any) => {
        this.jclxOptions = result.data;
      })
      .catch((err: object) => {
        console.log(err);
      });
  }
  // 查询当前表格数据
  queryAuxRealtimeList() {
    // 1.fzlStart和fzlEnd都得有值 或者都没值 才能查
    if (!this.formData.fzlEnd && !this.formData.fzlStart) {
      this.formData.fzlType = "";
    } else if (this.formData.fzlEnd && this.formData.fzlStart) {
      if (Number(this.formData.fzlEnd) <= 80) {
        this.formData.fzlType = "80";
      } else if (Number(this.formData.fzlEnd) <= 100) {
        this.formData.fzlType = "100";
      } else if (Number(this.formData.fzlEnd) > 100) {
        this.formData.fzlType = "";
      }
    } else {
      this.$message({
        type:'warning',
        message:'负载率两个值缺一不可'
      })
      return false;
    }
    // 2.ywStart和ywEnd都得有值 或者都没值 才能查
    if (
      (!this.formData.ywEnd && this.formData.ywStart) ||
      (this.formData.ywEnd && !this.formData.ywStart)
    ) {
      this.$message({
        type:'warning',
        message:'油温两个值缺一不可'
      })
      return false;
    }
    // 3.查询的时候 fzlType置空
    if (this.searchValue == 1) {
      this.formData.fzlType = "";
    }
    let form = {
      city: this.formData.company, // 所属地市
      jcsjStart: this.formData.jctime == null ? "" : this.formData.jctime[0], // 检测开始时间
      jcsjEnd: this.formData.jctime == null ? "" : this.formData.jctime[1], // 检测结束时间
      dydj: this.formData.Voltage, // 电压等级
      fzlStart: this.formData.fzlStart, // 开始负载率
      fzlEnd: this.formData.fzlEnd, // 结束负载率
      fzllx: this.formData.fzlType, // 负载率类型
      page: this.pages.page, // 当前页
      size: this.pages.pageSize, // 每页条数
      whbz: this.formData.team, // 维护班组
      bdzId: this.formData.substation, // 变电站名称
      ywStart: this.formData.ywStart, // 开始油温
      ywEnd: this.formData.ywEnd, // 结束油温
    };
    (this as any).$services
      .mainLoadTowList({ data: form, method: "get" })
      .then((result: any) => {
        let data = result.data;
         let page = this.pages.page;
      let size = this.pages.pageSize;
        this.tableData = data.records.map((v, i) => {
        v.myIndex = (page - 1) * size + i + 1;
        return v;
      });
        console.log("主变负载二级页面列表:", data);
        this.pages.totalSize = data.total;
      })
      .catch((err: object) => {
        console.log(err);
      });

    this.searchValue = 0;
  }

  // private init() {
  //   // 获取隐患柱状图数据
  //   (this as any).$services
  //     .hiddenDangerStatistics({
  //       method: "get",
  //       data: { localCity: this.localCity },
  //     })
  //     .then((result: any) => {
  //       console.log("隐患柱状图数据:", result);
  //       this.hiddenDangerStatistics = result.data[0];
  //     })
  //     .catch((err: object) => {
  //       console.log(err);
  //     });
  // }
  fzlLoading = false;
  public duty = [
    {
      name: "80%以下",
      value: 0,
      color: "#00C9FF",
    },
    {
      name: "80%-100%",
      value: 0,
      color: "#54A3FE",
    },
    {
      name: "100%以上",
      value: 0,
      color: "#EB6F49",
    },
  ];
  // 监听主编负载负载率
  get newMainLoadCount() {
    let mainLoadCount = lodash.cloneDeep(this.duty);
    let total =
      mainLoadCount[0].value + mainLoadCount[1].value + mainLoadCount[2].value;
    let mainArr = {
      total: total,
      typeOne: mainLoadCount[0].value,
      typeTwo: mainLoadCount[1].value,
      typeThree: mainLoadCount[2].value,
    };
    return mainArr;
  }
  fetchQuertInitZbfz() {
    this.fzlLoading = true;
    (this as any).$services
      .quertInitZbfz()
      .then((result: any) => {
        if (result.code === 200) {
          this.duty[0].value = result.data.down80 || 0;
          this.duty[1].value = result.data.down100 || 0;
          this.duty[2].value = result.data.on100 || 0;
        } else {
          this.duty[0].value = 0;
          this.duty[1].value = 0;
          this.duty[2].value = 0;
        }
        this.fzlLoading = false;
      })
      .catch((err: object) => {
        this.duty[0].value = 0;
        this.duty[1].value = 0;
        this.duty[2].value = 0;
        this.fzlLoading = false;
      });
  }
  mounted() {
    // console.log(
    //   "页面传参：",
    //   this.$route.params.dutySecondData,
    //   this.$route.params.dutyType
    // );
    this.fetchQuertInitZbfz();
    if (this.$route.params.dutySecondData) {
      let type = this.$route.params.dutyType;
      if (type == "0") {
        // 总数跳过来的
        this.formData.fzlStart = "";
        this.formData.fzlEnd = "";
        this.formData.fzlType = "";
      } else if (type == "1") {
        // 80%以下跳过来的
        this.formData.fzlStart = "0";
        this.formData.fzlEnd = "80";
        this.formData.fzlType = "80";
      } else if (type == "2") {
        // 80%-100%跳过来的
        this.formData.fzlStart = "80";
        this.formData.fzlEnd = "100";
        this.formData.fzlType = "100";
      } else if (type == "3") {
        // 100%以上跳过来的
        this.formData.fzlStart = "100";
        this.formData.fzlEnd = "";
        this.formData.fzlType = "100+";
      }
    }
    // 查询表格数据
    this.queryAuxRealtimeList();
  }
}
</script>

<style lang='scss' scoped>
.container {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  padding: 0 0.27rem;
  &-top {
    width: 100%;
    // height: 2%;
    // background-color: pink;
    display: flex;
    align-items: center;
    .back {
      width: 0.9rem;
      height: 0.31rem;
      margin-left: auto;
      background-image: url("../../../../assets/img/return.png");
      background-size: 100% 100%;
      background-repeat: no-repeat;
      background-position: center;
      cursor: pointer;
    }
  }
  .head {
    width: 100%;
    height: 26%;
    padding-top: 1%;
    // background-color: grey;
    // margin-bottom: 0.29rem;
    .echa {
      width: 100%;
      height: 100%;
      .echarts {
        width: 100%;
        height: 100%;
      }
    }
  }
  .center {
    width: 100%;
    height: 70%;
    padding-top: 1%;
    // background-color: pink;
    // margin-bottom: 0.38rem;
    .inspection-report-h {
      width: 100%;
      height: 100%;
      // padding: 0.24rem;
      .inspection-report-index {
        width: 100%;
        height: 100%;
        &-btn {
          display: flex;
          justify-content: flex-end;
        }
        .fromed {
          height: 120px;
        }
        .tableed {
          height: calc(100% - 180px);
        }
        .paged {
          height: 60px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
      .iconfont {
        cursor: pointer;
      }
    }
  }
  .bottom {
    width: 100%;
    // height: 56%;
    // background-color: rgb(179, 245, 177);
  }
}
</style>

<style lang="scss" scoped>
.table-query {
  width: 1.4rem;
}
</style>
